package com.parking.carsystem.parkingchargesystem.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Response;
import com.parking.carsystem.parkingchargesystem.R;
import com.parking.carsystem.parkingchargesystem.utils.Utils;
import com.parking.carsystem.parkingchargesystem.view.TBSWebView;
import com.tencent.smtt.sdk.TbsReaderView;

import java.io.File;


public class TbsReaderViewActivity extends BaseActivity {
    RelativeLayout rlContent;
    private TbsReaderView tbsReaderView;
    TBSWebView x5WebView;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_tbs;
    }

    public void initView() {
        String pdfUrl = getIntent().getStringExtra("pdfUrl");
        rlContent = findViewById(R.id.rl_content);
        //下面的回调必须要实现，暂时没找到此回调的用处
        //实例化TbsReaderView，然后将它装入我们准备的容器
        x5WebView = findViewById(R.id.x5WebView);
//        x5WebView.loadUrl("http://debugtbs.qq.com");
        tbsReaderView = new TbsReaderView(this, readerCallback);
        rlContent.addView(tbsReaderView, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//        downLoadFile("http://218.2.192.212:9000/aisino_cms/testpdf//150300201007206301/2020/04/08/7/bdd8d4b68d3b4f6a6230_1586328667672.pdf");
        downLoadFile(pdfUrl);
        File externalFilesDirs = Environment.getExternalStorageDirectory();
//        File externalFilesDirs = getExternalFilesDir("");
        File file = new File(externalFilesDirs.getAbsolutePath() + "/jindanke.docx");
        if (!file.exists()) {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_LONG).show();
            return;
        }
//        openOtherFile(file.getAbsolutePath(),"jindanke.docx");
    }

    public void initData() {

    }

    /**
     *
     * @param url
     */
    private void downLoadFile(String url) {
        final String fileName = parseFormat(url);
        String path = getExternalFilesDir("").getAbsolutePath();
        File file = new File(path+"/"+fileName);
        if(file.exists()){
            openOtherFile(file.getAbsolutePath(),fileName);
        }else {
            if (!TextUtils.isEmpty(url)) {
                //将含有中文的url进行encode
                String fileUrl = Utils.toUtf8String(url);
                OkGo.<File>get(fileUrl)
                        .execute(new FileCallback(getApplicationContext().getExternalFilesDir("").getAbsolutePath(), fileName) {
                            @Override
                            public void onSuccess(Response<File> response) {
                                stopLoading();
                                File file = getExternalFilesDir(fileName);
                                if (!file.exists()) {
                                    Toast.makeText(TbsReaderViewActivity.this, "文件不存在", Toast.LENGTH_LONG).show();
                                    return;
                                }
                                openOtherFile(file.getAbsolutePath(),fileName);
                            }

                            @Override
                            public void onError(Response<File> response) {
                                stopLoading();
                                showToast(response.message());
                                finish();
                            }
                        });
            } else {
                showToast("获取文件url失败");
                finish();
            }
        }
    }
    private String parseFormat(String url) {
        String fileName = null;
        try {
            fileName = url.substring(url.lastIndexOf("/") + 1);
        } finally {
            if (TextUtils.isEmpty(fileName)) {
                fileName = String.valueOf(System.currentTimeMillis());
            }
        }
        return fileName;
    }
    private String parseFormatold(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }
    private void openOtherFile(String path, String fileName) {
        Bundle bundle = new Bundle();
        bundle.putString("filePath", path);
//        bundle.putString("tempPath", Environment.getExternalStorageDirectory()
//                .getPath());
   bundle.putString("tempPath", getExternalFilesDir("").getAbsolutePath());

//        bundle.putString("tempPath", getExternalFilesDir("")
//                .getPath());
        String s = parseFormatold(fileName);
        boolean result = tbsReaderView.preOpen(s, false);
        if (result) {
            tbsReaderView.openFile(bundle);
        } else {
            File file = new File(path);
            if (file.exists()) {
                Intent openintent = new Intent();
                openintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                String type = getMIMEType(file);
                // 设置intent的data和Type属性。
                openintent.setDataAndType(/* uri */Uri.fromFile(file), type);
                // 跳转
                startActivity(openintent);
                finish();
            }
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //需要将预览服务停止，一定不要忘了
        if (tbsReaderView != null) {
            tbsReaderView.onStop();
        }
        x5WebView.reload();
        //销毁
        x5WebView.clearCache(true);
        x5WebView.clearFormData();
        x5WebView.destroy();
        tbsReaderView.onStop();
    }
    private String getMIMEType(File file) {

        String type = "*/*";
        String fName = file.getName();
        // 获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }
        /* 获取文件的后缀名 */
        String end = fName.substring(dotIndex, fName.length()).toLowerCase();
        if (end == "")
            return type;
        // 在MIME和文件类型的匹配表中找到对应的MIME类型。
        for (int i = 0; i < MIME_MapTable.length; i++) {
            if (end.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }
    private final String[][] MIME_MapTable = {
            // {后缀名，MIME类型}
            {".3gp", "video/3gpp"},
            {".apk", "application/vnd.android.package-archive"},
            {".asf", "video/x-ms-asf"},
            {".avi", "video/x-msvideo"},
            {".bin", "application/octet-stream"},
            {".bmp", "image/bmp"},
            {".c", "text/plain"},
            {".class", "application/octet-stream"},
            {".conf", "text/plain"},
            {".cpp", "text/plain"},
            {".doc", "application/msword"},
            {".docx",
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {".xls", "application/vnd.ms-excel"},
            {".xlsx",
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            {".exe", "application/octet-stream"},
            {".gif", "image/gif"},
            {".gtar", "application/x-gtar"},
            {".gz", "application/x-gzip"},
            {".h", "text/plain"},
            {".htm", "text/html"},
            {".html", "text/html"},
            {".jar", "application/java-archive"},
            {".java", "text/plain"},
            {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"},
            {".js", "application/x-javascript"},
            {".log", "text/plain"},
            {".m3u", "audio/x-mpegurl"},
            {".m4a", "audio/mp4a-latm"},
            {".m4b", "audio/mp4a-latm"},
            {".m4p", "audio/mp4a-latm"},
            {".m4u", "video/vnd.mpegurl"},
            {".m4v", "video/x-m4v"},
            {".mov", "video/quicktime"},
            {".mp2", "audio/x-mpeg"},
            {".mp3", "audio/x-mpeg"},
            {".mp4", "video/mp4"},
            {".mpc", "application/vnd.mpohun.certificate"},
            {".mpe", "video/mpeg"},
            {".mpeg", "video/mpeg"},
            {".mpg", "video/mpeg"},
            {".mpg4", "video/mp4"},
            {".mpga", "audio/mpeg"},
            {".msg", "application/vnd.ms-outlook"},
            {".ogg", "audio/ogg"},
            {".pdf", "application/pdf"},
            {".png", "image/png"},
            {".pps", "application/vnd.ms-powerpoint"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".pptx",
                    "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
            {".prop", "text/plain"}, {".rc", "text/plain"},
            {".rmvb", "audio/x-pn-realaudio"}, {".rtf", "application/rtf"},
            {".sh", "text/plain"}, {".tar", "application/x-tar"},
            {".tgz", "application/x-compressed"}, {".txt", "text/plain"},
            {".wav", "audio/x-wav"}, {".wma", "audio/x-ms-wma"},
            {".wmv", "audio/x-ms-wmv"},
            {".wps", "application/vnd.ms-works"}, {".xml", "text/plain"},
            {".z", "application/x-compress"},
            {".zip", "application/x-zip-compressed"}, {"", "*/*"}};
    TbsReaderView.ReaderCallback readerCallback = new TbsReaderView.ReaderCallback() {
        @Override
        public void onCallBackAction(Integer integer, Object o, Object o1) {

        }
    };

}
